using System;
using System.Web.UI;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Web;
using System.Security.Permissions;
using System.Text;

namespace SharpPieces.Web.JQuery
{

    /// <summary>
    /// Represents the base class for SharpPieces JQuery extender controls.
    /// </summary>
    [DefaultProperty("TargetControlID")]
    public abstract class BaseJQueryExtender : BaseJQueryControl
    {

        /// <summary>
        /// Resolves the target control.
        /// </summary>
        protected virtual Control ResolveTargetControl()
        {
            return this.ResolveTargetControl<Control>();
        }

        /// <summary>
        /// Resolves the target control.
        /// </summary>
        /// <param name="assignableTo">The assignable to type; it can be null.</param>
        protected virtual T ResolveTargetControl<T>()
            where T : Control
        {
            Control targetControl = this.NamingContainer.FindControl(this.TargetControlID);
            if (null == targetControl)
            {
                throw new ArgumentException("Invalid TargetControlID.");
            }
            if ((null != typeof(T)) && !typeof(T).IsAssignableFrom(targetControl.GetType()))
            {
                throw new ArgumentException(string.Format("Invalid TargetControlID. The target type should be {0} or above.", typeof(T).Name));
            }
            return targetControl as T;
        }

        /// <summary>
        /// Converts a list of options to JavaScript representation.
        /// </summary>
        /// <param name="list">The options list.</param>
        internal static string OptionListToJS(IDictionary<string, string> list)
        {            
            if ((null != list)&& (0 < list.Count))
            {
                StringBuilder sb = new StringBuilder("{");
                foreach (KeyValuePair<string, string> option in list)
                {
                    sb.Append(string.Concat(option.Key, ":", option.Value, ","));
                }
                return sb.Replace(",", "}", sb.Length - 1, 1).ToString();
            }
            return "null";
        }


        // Properties

        /// <summary>
        /// Gets or sets the target control ID.
        /// </summary>
        /// <value>The target control ID.</value>
        [Description("The target control ID."), Category("Behavior"), DefaultValue("")]
        [Themeable(false), IDReferenceProperty]
        public virtual string TargetControlID
        {
            get { return this.ViewState["TargetControlID"] as string ?? string.Empty; }
            set { this.ViewState["TargetControlID"] = value; }
        }

    }

}



 
